package com.spice.im.group;

import android.app.Activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Parcelable;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;

//import com.feiyangweilai.base.enviroment.DebugLog;
//import com.feiyangweilai.client.hairstyleshow.SplashActivity;
//import com.ishowtu.hairfamily.R;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 与UI相关的帮助类
 * 
 * @author buptzhaofang@163.com 2015-7-7
 *
 */
public final class UIUtils {
	private static final String TAG = UIUtils.class.getSimpleName();

	private UIUtils() {}

	/**
	 * 根据手机的分辨率从dip单位转化成px(像素)
	 */
	public static int dip2px(Context context, double dpVal) {
		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpVal * scale + 0.5);
	}

	/**
	 * 根据手机的分辨率从 px(像素)单位转化成dip
	 */
	public static int px2dip(Context context, double pxVal) {
		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxVal / scale + 0.5);
	}

	/**
	 * 根据手机分辨率从sp 单位转化成px(像素)
	 */
	public static int sp2px(Context context, float spVal) {
		float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
		return (int) (spVal * fontScale + 0.5f);
	}

	/**
	 * 获取状态栏的高度
	 * 
	 * @param window
	 *            窗口
	 * @return 状态栏高度(px)
	 */
	public static int getStatusBarHeight(Window window) {
		int statusBarHeight = 0;
		if (null != window) {
			// 获取状态栏的高度
			Rect frame = new Rect();
			window.getDecorView().getWindowVisibleDisplayFrame(frame);
			statusBarHeight = frame.top;
		}
		if (0 == statusBarHeight)
			statusBarHeight = 50;
		return statusBarHeight;
	}

	/**
	 * 在OnCreate时获取某控件的高度
	 * 
	 * @param view
	 *            目标控件
	 * @return 高度(px)
	 */
	public static int getMeasureHeightOnCreate(View view) {
		int w = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		int h = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		view.measure(w, h);
		return view.getMeasuredHeight();
	}

	/**
	 * 在OnCreate时获取控件宽度
	 * @param view
	 * @return
	 */
	public static int getMeasureWidthOnCreate(View view){
		int w = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		int h = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		view.measure(w, h);
		return view.getMeasuredWidth();
	}
	
	/**
	 * 显示或隐藏状态栏
	 * 
	 * @param window
	 *            窗口
	 * @param show
	 *            是否显示
	 */
	public static void showOrHideStatusBar(Window window, boolean show) {
		if (null == window)
			return;
		WindowManager.LayoutParams lp = window.getAttributes();
		if (show) {
			lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
			window.setAttributes(lp);
			window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
		} else {
			lp.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
			window.setAttributes(lp);
			window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
		}
	}

	/**
	 * 弹出软键盘
	 * 
	 * @param context
	 *            上下文
	 * @param view
	 *            在哪个视图上显示
	 */
	public static void showSoftInput(Context context, View view) {
		if (context == null || view == null)
			return;

		final InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (null != imm)
			imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
	}

	/**
	 * 弹出软键盘
	 * 
	 * @param context
	 *            上下文
	 * @param view
	 *            在哪个视图上显示
	 * @param delayTime
	 *            延迟时间（ms）
	 */
	public static void showSoftInputDelayed(final Context context,
			final View view, int delayTime) {
		if (null == context || null == view || delayTime < 0)
			return;
		if (delayTime == 0)
			showSoftInput(context, view);
		else {
			// 开启定时器进行延迟
			Timer timer = new Timer();
			timer.schedule(new TimerTask() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					showSoftInput(context, view);
				}
			}, delayTime);
		}
	}

	/**
	 * 隐藏软键盘
	 * 
	 * @param context
	 *            上下文
	 * @param View
	 *            在哪个视图上显示
	 */
	public static void hideSoftInput(Context context, View view) {
		if (null == context || null == view)
			return;

		InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		// 判断软键盘是否在显示
		if (imm != null && imm.isActive(view)) {
			imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
		}
	}

	/**
	 * 输入法是否已激活
	 * 
	 * @param context
	 * @param packageName
	 *            输入法应用的包名
	 * @return
	 */
	public static boolean isInputMethodEnabled(Context context,
			String packageName) {
		return getEnableInputMethodInfor(context, packageName) != null;
	}

	/**
	 * 获取已激活输入法的详细信息
	 * 
	 * @param context
	 * @param packageName
	 *            输入法应用的包名
	 * @return
	 */
	public static InputMethodInfo getEnableInputMethodInfor(Context context,
			String packageName) {
		if (packageName == null) {
			return null;
		}
		final InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		List<InputMethodInfo> imeInfoList = imm.getEnabledInputMethodList();

		if (imeInfoList != null) {
			for (InputMethodInfo imeInfo : imeInfoList) {
				if (packageName.equals(imeInfo.getPackageName())) {
					return imeInfo;
				}
			}
		}
		return null;
	}

	/**
	 * 输入法是否已启用
	 * 
	 * @param context
	 * @param packageName
	 *            输入法应用的包名
	 * @return
	 */
	public static boolean isInputMethodInUse(Context context, String packageName) {
		InputMethodInfo imeInfo = getEnableInputMethodInfor(context,
				packageName);
		if (imeInfo != null) {
			String ourId = imeInfo.getId();
			// 当前输入法id
			String curId = android.provider.Settings.Secure.getString(
					context.getContentResolver(),
					android.provider.Settings.Secure.DEFAULT_INPUT_METHOD);

			if (ourId != null && ourId.equals(curId)) {
				return true;
			}
			return false;
		}
		return false;
	}

	private static class XY {
		// 含有2个元素的一维数组，表示距离屏幕左上角的点，此处作为一个域变量是为了避免重复new
		private static int[] locationOfViewOnScreen = new int[2];
	}

	/**
	 * 判断触摸点是否在给定的view上
	 * 
	 * @param event
	 *            触摸事件
	 * @param view
	 *            给定的view
	 * @return
	 */
	public static boolean isInMyView(MotionEvent event, View view) {
		// 如果此时view被隐藏掉了，触摸点肯定不会落在此view上
		if (view.getVisibility() == View.GONE) {
			return false;
		}

		// 获取此view在屏幕上的位置（以屏幕左上角为参照点）
		view.getLocationOnScreen(XY.locationOfViewOnScreen);

		// 获取触摸点相对于屏幕左上角的偏移量
		float rawX = event.getRawX();
		float rawY = event.getRawY();

		// 如果触摸点处于此view的矩形区域内
		return rawX >= XY.locationOfViewOnScreen[0]
				&& rawX <= (XY.locationOfViewOnScreen[0] + view.getWidth())
				&& rawY >= XY.locationOfViewOnScreen[1]
				&& rawY <= (XY.locationOfViewOnScreen[1] + view.getHeight());
	}

	/**
	 * 设置在系统中改变字体大小不会影响我们的自体大小，如要考虑到美观
	 * 此方法只在第一个Activity中调用就可以了，不需要在所有的Activity中调用
	 * 
	 * @param activity
	 */
	public static void remainFont(Activity activity) {
		Resources resources = activity.getResources();
		Configuration configuration = resources.getConfiguration();
		configuration.fontScale = 1.0f;
		resources.updateConfiguration(configuration, null);
	}

	/**
	 * 设置屏幕方向
	 * 
	 * @param activity
	 *            要设置屏幕方向的Activity
	 * @param portrait
	 *            是否是竖屏
	 */
	public static void changeScreenOrientation(Activity activity,
			boolean portrait) {
		if (activity == null) {
			return;
		}

		if (portrait) {
			activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		} else {
			activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		}
	}

	/**
	 * 截图 截图会引用一个bitmap对象，有时候会很大，需要释放调用view.destroyDrawingCache();
	 * 
	 * @param view
	 *            要截图的对象
	 * @return 截图
	 */
	public static Bitmap snapshot(View view) {
		if (view == null) {
			return null;
		}

		// 先销毁旧的
		view.destroyDrawingCache();

		// 设置为可以截图
		view.setDrawingCacheEnabled(true);

		// 获取截图
		return view.getDrawingCache();
	}
	
	/**
	 * 判断快捷方式是否存在
	 * @return
	 */
//	public static boolean isShortCutExist(Context context){
//		ContentResolver cr=context.getContentResolver();
//		String AUTHORITY=getAuthorityFromPermission(context,"com.android.launcher.permission.READ_SETTINGS");
//		Uri CONTENT_URI= Uri.parse("content://" +
//				AUTHORITY + "/favorites?notify=true");
//		Cursor c=cr.query(CONTENT_URI, new String[]{"title","iconResource"},
//				"title=?", new String[]{context.getString(R.string.app_name).trim()},
//				null);
//		if(null!=c&&c.getCount()>0)
//			return true;
//		return false;
//	}

	/**
	 * 获取授权名
	 * @param context
	 * @param permission
	 * @return
	 */
	private static String getAuthorityFromPermission(Context context, String permission){
	    if (permission == null) return null;
	    List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(PackageManager.GET_PROVIDERS);
	    if (packs != null) {
	        for (PackageInfo pack : packs) {
	            ProviderInfo[] providers = pack.providers;
	            if (providers != null) { 
	                for (ProviderInfo provider : providers) {
	                    if (permission.equals(provider.readPermission)) return provider.authority;
	                    if (permission.equals(provider.writePermission)) return provider.authority;
	                } 
	            }
	        }
	    }
	    return null;
	}
	
	/**
	 * 创建快捷方式
	 * @param context
	 */
//	public static void createShortCut(Context context){
//		Intent shortcutIntent=new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
//		//不允许重复创建
//		shortcutIntent.putExtra("duplicate", false);
//		//需要显示的名称
//		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getString(R.string.app_name));
//		//快捷方式的图片
//		Parcelable icon= Intent.ShortcutIconResource.fromContext(context.getApplicationContext(), R.drawable.ic_launcher);
//		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
//		//点击快捷图片，运行程序的主入口
//		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(context.getApplicationContext(),SplashActivity.class));
//		//发送广播
//		context.sendBroadcast(shortcutIntent);
//	}
	
	/**
	 * 获取字体高度
	 * @param fontSize 字体大小
	 * @return
	 */
	public static int getFontHeight(float fontSize)  
	{  
	     Paint paint = new Paint();
	     paint.setTextSize(fontSize);  
	     FontMetrics fm = paint.getFontMetrics();
	    return (int) Math.ceil(fm.descent - fm.ascent);
	}  

//	/**
//	 * 自定义Toast显示
//	 * 
//	 * @param text
//	 */
//	public static void showToast(String text){
//		CustomToast.makeText(SmartClassApplication.getApplicationInstance(), text, CustomToast.LENGTH_SHORT).show();
//	}
//	
//	/**
//	 * 自定义Toast显示
//	 * 
//	 * @param text
//	 */
//	public static void showToast(String text,long showTime){
//		CustomToast.makeText(SmartClassApplication.getApplicationInstance(), text, showTime).show();
//	}
	
	/**
	 * 获取NavigationBar高度
	 * @param activity
	 * @return
	 */
	public static int getNavigationBarHeight(Activity activity) {
		if(checkDeviceHasNavigationBar(activity)){
			Resources resources = activity.getResources();
			int resourceId = resources.getIdentifier("navigation_bar_height",
					"dimen", "android");
			//获取NavigationBar的高度
			int height = resources.getDimensionPixelSize(resourceId);
			return height;
		}
		return 0;
	}
	
	/**
	 * 判断虚拟按键是否存在
	 * @param context
	 * @return
	 */
	 private static boolean checkDeviceHasNavigationBar(Context context) {

	        boolean hasNavigationBar = false;
	        Resources rs = context.getResources();
	        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
	        if (id > 0) {
	            hasNavigationBar = rs.getBoolean(id);
	        }
	        try {
	            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
	            Method m = systemPropertiesClass.getMethod("get", String.class);
	            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
	            if ("1".equals(navBarOverride)) {
	                hasNavigationBar = false;
	            } else if ("0".equals(navBarOverride)) {
	                hasNavigationBar = true;
	            }
	        } catch (Exception e) {
//	            DebugLog.w(TAG, e);
	        	e.printStackTrace();
	        }


	        return hasNavigationBar;
	    }
}
